package hephaestus.model.transformer;

import java.io.FileWriter;
import java.io.IOException;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

public class TemplateItem {

	private Template template;

	private String fileName;

	private String inPath;

	private String outPath;

	public TemplateItem(String inPath, String outPath) {
		this.inPath = inPath;
		this.outPath = outPath;
		try {
			template = Velocity.getTemplate(inPath);
		} catch (ResourceNotFoundException e) {
			e.printStackTrace();
		} catch (ParseErrorException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public TemplateItem(String inPath, String outPath, String fileName) {
		this.inPath = inPath;
		this.outPath = outPath;
		this.fileName = fileName;

		try {
			template = Velocity.getTemplate(inPath);
		} catch (ResourceNotFoundException e) {
			e.printStackTrace();
		} catch (ParseErrorException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Executa o template
	 * 
	 * @param ctx
	 */
	public void build(VelocityContext ctx) {
		FileWriter fw;
		try {
			FileManager.createDir(outPath);
			fw = new FileWriter(outPath + "/" + fileName);
			template.merge(ctx, fw);
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getInPath() {
		return inPath;
	}

	public void setInPath(String inPath) {
		this.inPath = inPath;
	}

	public String getOutPath() {
		return outPath;
	}

	public void setOutPath(String outPath) {
		this.outPath = outPath;
	}

	public Template getTemplate() {
		return template;
	}

	public void setTemplate(Template template) {
		this.template = template;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public void formatFileName(String name) {
		this.fileName = fileName.replaceAll("[#][{]className[}]", name);
	}
}
